﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Model;

namespace YiYiTong.Rocket.Business.Third
{
    /// <summary>
    /// ip查找地区信息
    /// </summary>
    public class IpBiz
    {
        public static Tuple<bool, IpRespModel> GetCityByIp(string ip)
        {
            string txIpUrl = ConfigHelper.AppSetting<string>("tx_ip_url", "https://apis.map.qq.com/ws/location/v1/ip");
            string txKey = ConfigHelper.AppSetting<string>("tx_key", "CMVBZ-HPVKI-7QVGL-5E5OI-C5PUV-2JBX4");

            string postData = string.Format("ip={0}&key={1}&output=json", ip, txKey);
            try
            {
                LogHelper.Debug("腾讯ip定位,请求：" + postData);
                string str = HttpHelper.HttpGet(txIpUrl, postData);
                LogHelper.Debug("腾讯ip定位,响应：" + str);
                if (!string.IsNullOrEmpty(str))
                {
                    var resp = JsonHelper.Deserialize<TxIpResponse>(str);
                    if (resp.status == 0)
                    {
                        IpRespModel model = new IpRespModel();
                        model.ip = ip;
                        model.city = resp.result.ad_info.city;
                        model.district = resp.result.ad_info.district;
                        model.nation = resp.result.ad_info.nation;
                        model.province = resp.result.ad_info.province;

                        return new Tuple<bool, IpRespModel>(true, model);
                    }
                    else
                    {
                        LogHelper.Error("腾讯ip定位错误，原因：" + resp.message);
                        return new Tuple<bool, IpRespModel>(false, null);
                    }
                }
                else
                    return new Tuple<bool, IpRespModel>(false, null);
            }
            catch (Exception ex)
            {
                LogHelper.Error("腾讯ip定位异常，原因：" + ex.GetExcetionMessage());
                return new Tuple<bool, IpRespModel>(false, null);
            }
        }
    }

    public class TxIpResponse
    {
        public int status { get; set; }
        public string message { get; set; }

        public TxIpResult result { get; set; }
    }

    public class TxIpResult
    {
        public string ip { get; set; }
        public TxAdInfo ad_info { get; set; }
    }

    public class TxAdInfo
    {
        public string nation { get; set; }
        public string province { get; set; }
        public string city { get; set; }
        public string district { get; set; }
        public string adcode { get; set; }
    }
}
